package pers.cz.jefconfig.tools;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Arrays;

/**
 * @program: Reids
 * @description:
 * @author: Cheng Zhi
 * @create: 2023-04-13 20:23
 **/
public class JefByteBuffer {

    /**
     * 保存所有的标记点
     */
    private int[] markPocket = new int[2];

    ByteBuffer byteBuffer;

    private int index = 0;

    public JefByteBuffer(int capacity, boolean isUseLocalMem) {
        if (isUseLocalMem) {
            byteBuffer = ByteBuffer.allocateDirect(capacity);
        } else {
            byteBuffer =  ByteBuffer.allocate(capacity);
        }
    }

    public JefByteBuffer(ByteBuffer byteBuffer) {
        this.byteBuffer = byteBuffer;
    }

    /**
     * 切换模式
     */
    public Buffer flip() {
       return byteBuffer.flip();
    }

    public char read() {
        return (char) byteBuffer.get();
    }

    public void unread() {
        int position = byteBuffer.position();
        byteBuffer.position(position - 1);
    }
    public byte get() {
        return byteBuffer.get();
    }

    public void put(byte[] src) {
        byteBuffer.put(src);
    }

    public void put(byte bi) {
        byteBuffer.put(bi);
    }

    public void clear() {
        byteBuffer.clear();
    }

    public boolean isEnd() {

        int current = byteBuffer.position();
        int end = byteBuffer.limit();
        if (current == end) {
            return true;
        }

        return false;
    }
    /**
     * 打标记
     */
    public void mark() {
        int mark = byteBuffer.position();
        ensureCapacityInternal();
        markPocket[index] = mark;
        index ++;
    }

    /**
     * 去除标记
     */
    public void unmark() {
        index --;
        markPocket[index] = 0;
    }

    /**
     * 重置
     */
    public void reset() {
        index --;
        if (index < 0) {
            return;
        }
        int mark = markPocket[index];
        if (mark < 0) {
            return;
        }
        byteBuffer.position(mark);
    }

    /**
     * 为markPocket扩容
     */
    private void ensureCapacityInternal() {

        int oldCapacity = markPocket.length;
        if (index >= oldCapacity) {
            int newCapacity = oldCapacity + (oldCapacity >> 1);
            // minCapacity is usually close to size, so this is a win:
            markPocket = Arrays.copyOf(markPocket, newCapacity);
        }
    }
}
